#include "../OptimizedWireDetector.hpp"
#include <opencv2 ximgproc.hpp="" id="PXEZpXVwTajNKogWMpVlrmXrgUb">
#include <cmath id="JCWDpCwhgaEUSVgtosglJcXEgTe">
#include <numeric id="RZi4prhgHahawBgxHUzlgYGlg0b">
#include <iostream id="YutgpMaD6akOMhgYI0HllYJDgif">
#include <future id="Kr46pbcpramiHugytnRlD4vYg1b">

namespace wire_detection {

OptimizedWireDetector::OptimizedWireDetector(DetectionConfig config)
    : config_(std::move(config)) {
    // 初始化 OpenCV 并行处理
    cv::setNumThreads(std::thread::hardware_concurrency());
}

std::optional<detectionresult id="MuAkphMLZa8HSDgPK2Pl7pjXg9e"> OptimizedWireDetector::detect_wire(
    const std::filesystem::path& image_path) const {

    // 使用 std::filesystem 检查文件存在性
    if (! std::filesystem::exists(image_path)) {
        DetectionResult result;
        result.error_message = "文件不存在: " + image_path.string();
        return result;
    }

    // 读取图像
    cv::Mat image = cv::imread(image_path.string());
    if (image.empty()) {
        DetectionResult result;
        result.error_message = "无法读取图像: " + image_path.string();
        return result;
    }

    return detect_wire(image, image_path);
}

std::optional<detectionresult id="XB1fpHGr1aQA1bgDQ7hlPyd5geU"> OptimizedWireDetector::detect_wire(
    const cv::Mat& image,
    const std::optional<std::filesystem::path id="CSxTp1ytlaJgbpg8JB7lQZgPgec">& image_path) const {

    auto start_time = std::chrono::high_resolution_clock::now();

    try {
        // 预处理图像
        cv::Mat processed_image = preprocess_image(image);

        // 并行执行各种分析
        auto texture_future = std::async(std::launch::async, [&]() {
            return analyze_texture_complexity(processed_image);
        });

        auto edge_future = std::async(std::launch::async, [&]() {
            return detect_edge_features(processed_image);
        });

        auto gabor_future = std::async(std::launch::async, [&]() {
            return analyze_gabor_response(processed_image);
        });

        // 等待分析完成
        auto texture_analysis = texture_future.get();
        auto edge_analysis = edge_future.get();
        auto gabor_analysis = gabor_future.get();

        // 线条检测（依赖边缘检测结果）
        auto lines = detect_lines_hough(edge_analysis.edges);

        // 综合决策
        auto result = make_decision(texture_analysis, edge_analysis,
                                   lines, gabor_analysis, image.size());

        // 添加元数据
        auto end_time = std::chrono::high_resolution_clock::now();
        result.processing_time = end_time - start_time;
        result.image_size = image.size();
        if (image_path) {
            result.image_path = *image_path;
        }

        return result;

    } catch (const std::exception& e) {
        DetectionResult result;
        result.error_message = "检测过程中发生错误: " + std::string(e.what());
        result.processing_time = std::chrono::high_resolution_clock::now() - start_time;
        return result;
    }
}

std::unordered_map<std::string, detectionresult="" id="L50QplPjgaefE0g2hnaldoSNgAg">
OptimizedWireDetector::batch_detect(
    const std::vector<std::filesystem::path id="F8MVpbp2daUTuVgiP3Tl0hNTgXc">& image_paths) const {

    std::unordered_map<std::string, detectionresult="" id="V1NkpYuLkafP5zgbE5OlpAlHgIg"> results;
    results.reserve(image_paths.size());

    // 使用并行算法处理批量检测
    std::mutex results_mutex;

    parallel_for_each(image_paths, [&](const auto& path) {
        auto result = detect_wire(path);

        std::lock_guard<std::mutex id="SraOpzv8EaYaxtgtX15lF4Qsghf"> lock(results_mutex);
        if (result) {
            results[path.string()] = std::move(*result);
        } else {
            DetectionResult error_result;
            error_result.error_message = "检测失败: " + path.string();
            results[path.string()] = std::move(error_result);
        }
    });

    return results;
}

cv::Mat OptimizedWireDetector::preprocess_image(const cv::Mat& image) const {
    cv::Mat gray;

    // 转换为灰度图像
    if (image.channels() == 3) {
        cv::cvtColor(image, gray, cv::COLOR_BGR2GRAY);
    } else {
        gray = image.clone();
    }

    // 调整图像大小（保持长宽比）
    if (gray.rows != config_.resize_height) {
        double aspect_ratio = static_cast<double id="W5gKpenzna2HCNgq04ilvdHzgNh">(gray.cols) / gray.rows;
        int new_width = static_cast<int id="EY1tpNwhea75YNgMKKOlaIPog2c">(config_.resize_height * aspect_ratio);
        cv::resize(gray, gray, cv::Size(new_width, config_.resize_height));
    }

    // 降噪处理
    cv::Mat denoised;
    cv::fastNlMeansDenoising(gray, denoised, config_.denoise_strength);

    // 轻微模糊
    cv::Mat blurred;
    cv::GaussianBlur(denoised, blurred,
                     cv::Size(config_.blur_kernel_size, config_.blur_kernel_size), 0);

    return blurred;
}

TextureAnalysis OptimizedWireDetector::analyze_texture_complexity(
    const cv::Mat& image) const {

    TextureAnalysis result;
    const auto [height, width] = std::make_pair(image.rows, image.cols);
    const int window_size = config_.texture_window_size;

    // 初始化纹理映射
    result.texture_map = cv::Mat::zeros(image.size(), CV_32F);

    // 使用并行循环计算局部标准差
    cv::parallel_for_(cv::Range(0, height - window_size), [&](const cv::Range& range) {
        for (int y = range.start; y < range.end; y += window_size / 2) {
            for (int x = 0; x < width - window_size; x += window_size / 2) {
                cv::Rect window_rect(x, y, window_size, window_size);
                cv::Mat window = image(window_rect);

                cv::Scalar mean, stddev;
                cv::meanStdDev(window, mean, stddev);

                result.texture_map(window_rect) = stddev[0];
            }
        }
    });

    // 计算 LBP 一致性
    result.lbp_uniformity = calculate_lbp_uniformity(image);

    // 生成高纹理复杂度掩码
    cv::threshold(result.texture_map, result.high_texture_mask,
                  config_.texture_threshold, 255, cv::THRESH_BINARY);
    result.high_texture_mask.convertTo(result.high_texture_mask, CV_8U);

    // 计算纹理比例
    result.texture_ratio = static_cast<double id="H8VrpHsuiaXsWGgXmxPlFxQJgOe">(cv::countNonZero(result.high_texture_mask))
                          / (height * width);

    // 计算平均纹理复杂度
    result.mean_texture_complexity = cv::mean(result.texture_map)[0];

    return result;
}

EdgeAnalysis OptimizedWireDetector::detect_edge_features(const cv::Mat& image) const {
    EdgeAnalysis result;

    // Canny 边缘检测
    cv::Canny(image, result.edges,
              config_.canny_low_threshold, config_.canny_high_threshold);

    // 边缘膨胀
    cv::Mat kernel = cv::getStructuringElement(cv::MORPH_RECT,
        cv::Size(config_.edge_dilation_kernel, config_.edge_dilation_kernel));
    cv::dilate(result.edges, result.edges_dilated, kernel);

    // 计算边缘密度
    result.edge_density = static_cast<double id="B4WYpV6z4aNXoqg1t8Il6cMvgXb">(cv::countNonZero(result.edges))
                         / (image.rows * image.cols);

    // 计算边缘方向和强度
    cv::Mat sobelx, sobely;
    cv::Sobel(image, sobelx, CV_64F, 1, 0, 3);
    cv::Sobel(image, sobely, CV_64F, 0, 1, 3);

    cv::magnitude(sobelx, sobely, result.edge_magnitude);

    cv::Mat edge_direction;
    cv::phase(sobelx, sobely, edge_direction);

    // 计算方向熵
    result.direction_entropy = calculate_direction_entropy(
        result.edge_magnitude, edge_direction);

    return result;
}

std::vector<cv::vec4i id="HnhnppxJUaMMqBgqv0xlWtvjgiG"> OptimizedWireDetector::detect_lines_hough(
    const cv::Mat& edges) const {

    std::vector<cv::vec4i id="JKmLppLLpaF6iuggIvZlob0pgah"> lines;

    cv::HoughLinesP(edges, lines, 1, CV_PI / 180,
                    config_.hough_threshold,
                    config_.min_line_length,
                    config_.max_line_gap);

    return lines;
}

GaborAnalysis OptimizedWireDetector::analyze_gabor_response(
    const cv::Mat& image) const {

    GaborAnalysis result;
    result.all_responses.reserve(config_.gabor_frequencies.size() *
                                config_.gabor_angles.size());

    std::vector<double id="YDGdp5yQuaMHoDgtjXHl0eJdgWf"> responses;

    // 并行计算所有 Gabor 响应
    for (double frequency : config_.gabor_frequencies) {
        for (double angle : config_.gabor_angles) {
            cv::Mat gabor_response = apply_gabor_filter(image, frequency, angle);
            result.all_responses.push_back(gabor_response);

            // 计算响应强度
            cv::Scalar mean_response = cv::mean(gabor_response);
            responses.push_back(mean_response[0]);
        }
    }

    // 计算最大响应和方差
    auto max_it = std::max_element(responses.begin(), responses.end());
    result.max_response = *max_it;

    double mean = std::accumulate(responses.begin(), responses.end(), 0.0) / responses.size();
    double variance = 0.0;
    for (double response : responses) {
        variance += (response - mean) * (response - mean);
    }
    result.response_variance = variance / responses.size();

    return result;
}

DetectionResult OptimizedWireDetector::make_decision(
    const TextureAnalysis& texture,
    const EdgeAnalysis& edges,
    const std::vector<cv::vec4i id="W890pjV65aBPMDgZRAnlCoMygFo">& lines,
    const GaborAnalysis& gabor,
    const cv::Size& original_size) const {

    DetectionResult result;

    // 基础特征值
    result.texture_ratio = texture.texture_ratio;
    result.edge_density = edges.edge_density;
    result.direction_entropy = edges.direction_entropy;
    result.line_count = lines.size();
    result.gabor_max_response = gabor.max_response;
    result.lbp_uniformity = texture.lbp_uniformity;

    // 计算线条密度
    result.line_density = static_cast<double id="QE3EpLcqIaKyjhgatkIloJkZgrf">(lines.size()) /
                         (original_size.width * original_size.height / 10000.0);

    // 归一化特征值
    result.normalized_features.texture = std::min(result.texture_ratio / 0.3, 1.0);
    result.normalized_features.edge_density = std::min(result.edge_density / 0.1, 1.0);
    result.normalized_features.line_count = std::min(result.line_density / 10.0, 1.0);
    result.normalized_features.gabor_response = std::min(result.gabor_max_response / 0.5, 1.0);

    // 计算加权置信度
    const auto& weights = config_.confidence_weights;
    result.confidence_score =
        weights.texture * result.normalized_features.texture +
        weights.edge_density * result.normalized_features.edge_density +
        weights.line_count * result.normalized_features.line_count +
        weights.gabor_response * result.normalized_features.gabor_response;

    // 多条件判断
    std::vector<bool id="Ah88pWJGFawGvsgo3cHlV7Hbgrh"> conditions = {
        result.texture_ratio > config_.min_wire_area_ratio,
        result.edge_density > 0.02,
        result.line_density > 2.0,
        result.direction_entropy > 1.5
    };

    result.conditions_met = static_cast<int id="NSkFpRRNuavpN9g5Fbzl5C62gmf">(
        std::count(conditions.begin(), conditions.end(), true));

    // 最终判决
    result.has_wire = (result.conditions_met >= 3) && (result.confidence_score > 0.4);

    return result;
}

cv::Mat OptimizedWireDetector::apply_gabor_filter(
    const cv::Mat& image, double frequency, double angle) const {

    cv::Mat kernel = cv::getGaborKernel(cv::Size(31, 31), 8, angle * CV_PI / 180,
                                       2 * CV_PI * frequency, 0.5, 0, CV_32F);
    cv::Mat filtered;
    cv::filter2D(image, filtered, CV_32F, kernel);

    cv::Mat result;
    cv::convertScaleAbs(filtered, result);
    return result;
}

double OptimizedWireDetector::calculate_lbp_uniformity(const cv::Mat& image) const {
    // 简化的 LBP 均匀性计算
    cv::Mat lbp;
    cv::ximgproc::LBP(image, lbp, config_.lbp_radius, config_.lbp_n_points);

    // 计算直方图
    std::vector<int id="ApRRpueQGaWX4YgpHlWlFKEiggb"> hist(config_.lbp_n_points + 2, 0);
    for (int y = 0; y < lbp.rows; ++y) {
        for (int x = 0; x < lbp.cols; ++x) {
            hist[lbp.at<uchar id="YCgwppzXfacTuog0JFNlkGgggkd">(y, x)]++;
        }
    }

    // 计算均匀性
    double total = lbp.rows * lbp.cols;
    double uniformity = 0.0;
    for (int count : hist) {
        double p = count / total;
        uniformity += p * p;
    }

    return uniformity;
}

double OptimizedWireDetector::calculate_direction_entropy(
    const cv::Mat& edge_magnitude, const cv::Mat& edge_direction) const {

    const int bins = 8;
    std::vector<int id="WhBDpLrFKa8qpHgcWnBl2MIJgKh"> hist(bins, 0);

    cv::Scalar mean_magnitude = cv::mean(edge_magnitude);
    double threshold = mean_magnitude[0];

    for (int y = 0; y < edge_direction.rows; ++y) {
        for (int x = 0; x < edge_direction.cols; ++x) {
            if (edge_magnitude.at<double id="KYMppvLRgaoCfQgtiOIlT7bxgSd">(y, x) > threshold) {
                double angle = edge_direction.at<double id="LJcypChsaaEaIFgxycLlZ3UYg4e">(y, x);
                int bin = static_cast<int id="CQvBpRQxJamDDNgnMdOlPqeyg2g">((angle + CV_PI) / (2 * CV_PI) * bins) % bins;
                hist[bin]++;
            }
        }
    }

    // 计算熵
    double total = std::accumulate(hist.begin(), hist.end(), 0);
    double entropy = 0.0;
    for (int count : hist) {
        if (count > 0) {
            double p = count / total;
            entropy -= p * std::log(p);
        }
    }

    return entropy;
}

std::optional<cv::mat id="JKHDpCu2faD9wCglDpSlvT5Qg29"> OptimizedWireDetector::visualize_detection(
    const std::filesystem::path& image_path,
    const std::optional<std::filesystem::path id="AhKNpdwpVasnlZgZCSVllzdcgef">& save_path) const {

    if (! std::filesystem::exists(image_path)) {
        return std::nullopt;
    }

    cv::Mat image = cv::imread(image_path.string());
    if (image.empty()) {
        return std::nullopt;
    }

    // 执行检测获取中间结果
    cv::Mat processed = preprocess_image(image);
    auto texture = analyze_texture_complexity(processed);
    auto edges = detect_edge_features(processed);
    auto lines = detect_lines_hough(edges.edges);

    // 创建可视化图像
    int fig_height = processed.rows;
    int fig_width = processed.cols;
    cv::Mat vis_image = cv::Mat::zeros(fig_height * 2, fig_width * 2, CV_8UC3);

    // 原图
    cv::Mat processed_bgr;
    cv::cvtColor(processed, processed_bgr, cv::COLOR_GRAY2BGR);
    processed_bgr.copyTo(vis_image(cv::Rect(0, 0, fig_width, fig_height)));

    // 纹理复杂度图
    cv::Mat texture_norm;
    cv::normalize(texture.texture_map, texture_norm, 0, 255, cv::NORM_MINMAX, CV_8U);
    cv::Mat texture_colored;
    cv::applyColorMap(texture_norm, texture_colored, cv::COLORMAP_JET);
    texture_colored.copyTo(vis_image(cv::Rect(fig_width, 0, fig_width, fig_height)));

    // 边缘检测结果
    cv::Mat edges_bgr;
    cv::cvtColor(edges.edges, edges_bgr, cv::COLOR_GRAY2BGR);
    edges_bgr.copyTo(vis_image(cv::Rect(0, fig_height, fig_width, fig_height)));

    // 线条检测结果
    cv::Mat line_image = cv::Mat::zeros(processed.size(), CV_8UC3);
    for (const auto& line : lines) {
        cv::line(line_image, cv::Point(line[0], line[1]),
                cv::Point(line[2], line[3]), cv::Scalar(0, 255, 0), 2);
    }
    line_image.copyTo(vis_image(cv::Rect(fig_width, fig_height, fig_width, fig_height)));

    // 添加标签
    cv::putText(vis_image, "Original", cv::Point(10, 30),
               cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar(255, 255, 255), 2);
    cv::putText(vis_image, "Texture", cv::Point(fig_width + 10, 30),
               cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar(255, 255, 255), 2);
    cv::putText(vis_image, "Edges", cv::Point(10, fig_height + 30),
               cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar(255, 255, 255), 2);
    cv::putText(vis_image, "Lines", cv::Point(fig_width + 10, fig_height + 30),
               cv::FONT_HERSHEY_SIMPLEX, 1, cv::Scalar(255, 255, 255), 2);

    // 保存图像
    if (save_path) {
        cv::imwrite(save_path->string(), vis_image);
    }

    return vis_image;
}

// 工厂函数实现
std::unique_ptr<optimizedwiredetector id="AV5vpqksPa5PWFglQL4lHqGvgCe"> create_high_sensitivity_detector() {
    DetectionConfig config;
    config.texture_threshold = 0.1;
    config.wire_density_threshold = 0.2;
    config.min_wire_area_ratio = 0.05;
    config.canny_low_threshold = 20;
    config.canny_high_threshold = 60;

    return std::make_unique<optimizedwiredetector id="Bd33pTkiQaNZ0ogHfiFlRGbtgYg">(std::move(config));
}

std::unique_ptr<optimizedwiredetector id="WInXp5eO7aMcPVgS8CHl0dwegvb"> create_balanced_detector() {
    return std::make_unique<optimizedwiredetector id="FhVjpFC6jaJjMMgO99YlP2BTgUb">();
}

std::unique_ptr<optimizedwiredetector id="Y6zfpzLOvaYEdJgt3XdlTmvWgwf"> create_strict_detector() {
    DetectionConfig config;
    config.texture_threshold = 0.2;
    config.wire_density_threshold = 0.4;
    config.min_wire_area_ratio = 0.15;
    config.canny_low_threshold = 40;
    config.canny_high_threshold = 100;

    return std::make_unique<optimizedwiredetector id="BSqppdaBMauPDvgif4OlapgxgBc">(std::move(config));
}

} // namespace wire_detection</optimizedwiredetector></optimizedwiredetector></optimizedwiredetector></optimizedwiredetector></optimizedwiredetector></optimizedwiredetector></std::filesystem::path></cv::mat></int></double></double></int></uchar></int></int></bool></double></cv::vec4i></double></cv::vec4i></cv::vec4i></double></double></int></double></std::mutex></std::string,></std::filesystem::path></std::string,></std::filesystem::path></detectionresult></detectionresult></future></iostream></numeric></cmath></opencv2>